<template>
  <div class="retention-strategy-panel">
    <!-- 用户风险评估 -->
    <div class="risk-assessment-section">
      <h3>用户风险评估</h3>
      <div class="risk-info">
        <div class="risk-level">
          <span class="label">流失风险等级:</span>
          <el-tag :type="getRiskTagType(user.riskLevel)" size="large">
            {{ getRiskLevelText(user.riskLevel) }}
          </el-tag>
        </div>
        <div class="risk-probability">
          <span class="label">流失概率:</span>
          <div class="probability-display">
            <el-progress 
              :percentage="Math.round(user.churnProbability * 100)" 
              :stroke-width="12"
              :color="getRiskColor(user.riskLevel)"
            />
            <span class="probability-text">{{ Math.round(user.churnProbability * 100) }}%</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 策略选择 -->
    <div class="strategy-selection-section">
      <h3>挽回策略选择</h3>
      <el-form :model="strategyForm" label-width="120px">
        <el-form-item label="策略类型">
          <el-select v-model="strategyForm.type" placeholder="请选择策略类型" style="width: 100%">
            <el-option 
              v-for="type in strategyTypes" 
              :key="type.value"
              :label="type.label" 
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="优惠力度">
          <el-slider
            v-model="strategyForm.discountLevel"
            :min="5"
            :max="50"
            :step="5"
            show-stops
            show-input
            :format-tooltip="formatDiscountTooltip"
          />
        </el-form-item>

        <el-form-item label="执行渠道">
          <el-checkbox-group v-model="strategyForm.channels">
            <el-checkbox label="email">邮件</el-checkbox>
            <el-checkbox label="sms">短信</el-checkbox>
            <el-checkbox label="push">APP推送</el-checkbox>
            <el-checkbox label="call">电话</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="执行时间">
          <el-date-picker
            v-model="strategyForm.executeTime"
            type="datetime"
            placeholder="选择执行时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="策略描述">
          <el-input
            v-model="strategyForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入策略描述"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 推荐策略模板 -->
    <div class="strategy-templates-section">
      <h3>推荐策略模板</h3>
      <div class="templates-grid">
        <div 
          v-for="template in recommendedTemplates" 
          :key="template.id"
          class="template-card"
          :class="{ active: selectedTemplate === template.id }"
          @click="selectTemplate(template)"
        >
          <div class="template-header">
            <h4>{{ template.name }}</h4>
            <el-tag :type="template.effectiveness" size="small">
              {{ getEffectivenessText(template.effectiveness) }}
            </el-tag>
          </div>
          <div class="template-content">
            <p>{{ template.description }}</p>
            <div class="template-metrics">
              <div class="metric">
                <span class="metric-label">成功率:</span>
                <span class="metric-value">{{ template.successRate }}%</span>
              </div>
              <div class="metric">
                <span class="metric-label">成本:</span>
                <span class="metric-value">{{ template.cost }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 预期效果预测 -->
    <div class="effect-prediction-section">
      <h3>预期效果预测</h3>
      <div class="prediction-metrics">
        <el-row :gutter="16">
          <el-col :span="8">
            <div class="prediction-card">
              <div class="prediction-icon">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="prediction-content">
                <h4>{{ predictedEffect.retentionRate }}%</h4>
                <p>预期挽回率</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="prediction-card">
              <div class="prediction-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="prediction-content">
                <h4>¥{{ predictedEffect.expectedRevenue.toLocaleString() }}</h4>
                <p>预期收入</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="prediction-card">
              <div class="prediction-icon">
                <el-icon><Star /></el-icon>
              </div>
              <div class="prediction-content">
                <h4>{{ predictedEffect.roi }}x</h4>
                <p>投资回报率</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="handleCancel">取消</el-button>
      <el-button @click="previewStrategy">预览策略</el-button>
      <el-button type="primary" @click="createStrategy" :loading="creating">
        创建策略
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { TrendCharts, Money, Star } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  user: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits(['strategy-created', 'cancel'])

// 响应式数据
const creating = ref(false)
const selectedTemplate = ref(null)

// 策略表单
const strategyForm = reactive({
  type: '',
  discountLevel: 20,
  channels: ['email', 'push'],
  executeTime: new Date(Date.now() + 24 * 60 * 60 * 1000), // 明天
  description: ''
})

// 策略类型
const strategyTypes = [
  { label: '优惠券策略', value: 'coupon' },
  { label: '个性化推荐', value: 'recommendation' },
  { label: '会员升级', value: 'membership' },
  { label: '客服关怀', value: 'service' },
  { label: '限时活动', value: 'activity' }
]

// 推荐策略模板
const recommendedTemplates = computed(() => {
  const baseTemplates = [
    {
      id: 1,
      name: '高价值用户挽回',
      description: '针对高价值用户的专属优惠和VIP服务',
      effectiveness: 'success',
      successRate: 85,
      cost: '高',
      strategy: {
        type: 'coupon',
        discountLevel: 30,
        channels: ['email', 'call'],
        description: '发送30%优惠券 + VIP客服专线服务'
      }
    },
    {
      id: 2,
      name: '个性化产品推荐',
      description: '基于用户历史购买行为的个性化产品推荐',
      effectiveness: 'primary',
      successRate: 72,
      cost: '中',
      strategy: {
        type: 'recommendation',
        discountLevel: 15,
        channels: ['push', 'email'],
        description: '推送个性化产品 + 15%新品折扣'
      }
    },
    {
      id: 3,
      name: '限时回归活动',
      description: '限时特价活动，营造紧迫感促进购买',
      effectiveness: 'warning',
      successRate: 68,
      cost: '低',
      strategy: {
        type: 'activity',
        discountLevel: 25,
        channels: ['sms', 'push'],
        description: '48小时限时25%折扣活动'
      }
    }
  ]

  // 根据用户风险等级调整推荐
  if (props.user.riskLevel === 'High') {
    return baseTemplates.sort((a, b) => b.successRate - a.successRate)
  }
  return baseTemplates
})

// 预期效果
const predictedEffect = computed(() => {
  const baseRetention = 45
  const discountBonus = strategyForm.discountLevel * 0.8
  const channelBonus = strategyForm.channels.length * 5
  
  const retentionRate = Math.min(95, baseRetention + discountBonus + channelBonus)
  const expectedRevenue = Math.round(props.user.avgOrderValue * retentionRate / 100 * 1.2)
  const roi = (expectedRevenue / (props.user.avgOrderValue * strategyForm.discountLevel / 100)).toFixed(1)

  return {
    retentionRate: Math.round(retentionRate),
    expectedRevenue,
    roi
  }
})

// 方法
const getRiskTagType = (riskLevel) => {
  const typeMap = {
    'High': 'danger',
    'Medium': 'warning',
    'Low': 'success'
  }
  return typeMap[riskLevel] || 'info'
}

const getRiskLevelText = (riskLevel) => {
  const textMap = {
    'High': '高风险',
    'Medium': '中风险',
    'Low': '低风险'
  }
  return textMap[riskLevel] || '未知'
}

const getRiskColor = (riskLevel) => {
  const colorMap = {
    'High': '#F56C6C',
    'Medium': '#E6A23C',
    'Low': '#67C23A'
  }
  return colorMap[riskLevel] || '#909399'
}

const getEffectivenessText = (effectiveness) => {
  const textMap = {
    'success': '高效',
    'primary': '推荐',
    'warning': '一般'
  }
  return textMap[effectiveness] || '未知'
}

const formatDiscountTooltip = (value) => {
  return `${value}% 折扣`
}

const selectTemplate = (template) => {
  selectedTemplate.value = template.id
  Object.assign(strategyForm, template.strategy)
}

const previewStrategy = () => {
  ElMessage.info('策略预览功能开发中...')
}

const createStrategy = async () => {
  if (!strategyForm.type) {
    ElMessage.warning('请选择策略类型')
    return
  }

  if (strategyForm.channels.length === 0) {
    ElMessage.warning('请选择至少一个执行渠道')
    return
  }

  creating.value = true
  
  try {
    // 模拟创建策略
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    const strategy = {
      userId: props.user.userId,
      userName: props.user.userName,
      ...strategyForm,
      predictedEffect: predictedEffect.value,
      createdAt: new Date().toISOString()
    }
    
    emit('strategy-created', strategy)
    ElMessage.success('挽回策略创建成功')
  } catch (error) {
    ElMessage.error('策略创建失败')
  } finally {
    creating.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 监听器
watch(() => strategyForm.type, (newType) => {
  // 根据策略类型调整默认参数
  if (newType === 'coupon') {
    strategyForm.discountLevel = 25
  } else if (newType === 'membership') {
    strategyForm.discountLevel = 15
  }
})
</script>

<style scoped>
.retention-strategy-panel {
  padding: 20px 0;
}

.risk-assessment-section,
.strategy-selection-section,
.strategy-templates-section,
.effect-prediction-section {
  margin-bottom: 32px;
}

.risk-assessment-section h3,
.strategy-selection-section h3,
.strategy-templates-section h3,
.effect-prediction-section h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 8px;
}

/* 风险评估 */
.risk-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.risk-level,
.risk-probability {
  display: flex;
  align-items: center;
  gap: 12px;
}

.risk-level .label,
.risk-probability .label {
  font-size: 14px;
  color: #666;
  min-width: 100px;
}

.probability-display {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.probability-display .el-progress {
  flex: 1;
  max-width: 200px;
}

.probability-text {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 策略模板 */
.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.template-card {
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.template-card:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.template-card.active {
  border-color: #409EFF;
  background: #f0f9ff;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.template-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.template-content p {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.template-metrics {
  display: flex;
  gap: 16px;
}

.metric {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #999;
}

.metric-value {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

/* 预期效果 */
.prediction-metrics {
  margin-top: 16px;
}

.prediction-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
}

.prediction-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.prediction-content h4 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 700;
  color: #333;
}

.prediction-content p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .templates-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .risk-level,
  .risk-probability {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .probability-display {
    width: 100%;
  }
}
</style>
